<?php

namespace App\Http\Controllers\Admin;

use App\Models\AdminRoleRule;
use Illuminate\Http\Request;
use Gregwar\Captcha\CaptchaBuilder;
use App\Http\Requests\Aadmin\Login\LoginRequest;
use App\Models\User;
use App\Models\AdminRule;
use Illuminate\Support\Facades\DB;

class LoginController extends AdminBaseController
{

    public function index(LoginRequest $request,User $user)
    {
        if ($request->isMethod('post'))
        {
            $post = $request->input();

            $this->set_login_session($post);

            $jump_url = $this->get_login_jump_url(config('admin.login_url'));

            $user->updateLoginById(session('user.id'));

            return ['code' => self::SUCESS_CODE, 'msg' => '登陆成功', 'jump_url' => url($jump_url)];

        } else {

            return view('admin.login.index');

        }

    }

    protected function set_login_session(array $data)
    {
        $userResult = User::where('username', $data['username'])->first();

        session([
            'user' => [
                'id' 	   => $userResult->id,
                'username' => $userResult->username,
                'role_id'  => $userResult->role_id,
            ]
        ]);

        if ($userResult->id == 1){ //超级管理员
            $ruleList = AdminRule::query()->orderBy('weight','desc')->get(['id', 'pid', 'name', 'is_menu', 'url', 'icon','route']);
        } else {
            //$ruleResult = AdminRoleRule::with('rules')->where('role_id',$userResult->id)->get()->toArray();
            $ruleList = DB::table('admin_role_rules as role_rules')
                ->leftJoin('admin_rules as rules','role_rules.rule_id','=','rules.id')
                ->where('role_id',$userResult->id)
                ->whereNull('deleted_at')
                ->orderBy('weight','desc')
                ->get(['rules.id', 'rules.pid', 'rules.name', 'is_menu', 'url', 'icon','route']);
        }

        $ruleUrls = $menuList = [];
        foreach($ruleList as $rule){
            $ruleUrls[$rule->url] = $rule->pid;
            if ($rule->is_menu == 1){
                $menuList[] = $rule->toArray();
            }
        }

        /*缓存用户有权限url 或 路由*/
        session(['rule_urls' => $ruleUrls]);
        /*缓存导航*/
        session(['menu_list' => get_menu_tree($menuList)]);

    }

    /** 登出
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function logout()
    {
        session()->flush();
        return redirect()->route('login');
    }

    /** 生成图片验证码
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     * @throws \Exception
     */
    public function verifycode()
    {
        $phrase = (new \Gregwar\Captcha\PhraseBuilder())->build(4, 'abcdefghijkmnpqrstuvwxy3456789');
        $builder = new CaptchaBuilder($phrase);
        $builder->build($width = 116, $height = 37);
        session(['loginVerifyCode' => $builder->getPhrase()]);
        header("Cache-Control: no-cache, must-revalidate");

        return response($builder->output())->header('Content-type', 'image/jpeg');
    }

    /** 获取登陆跳转地址
     * @param $url
     * @return mixed
     */
    protected function get_login_jump_url($url)
    {
        $urls = session('rule_urls');
        if (isset($urls[$url])) {
            return $url;
        }

        $allow_jump = ['admin/index/console'];
        foreach ($allow_jump as $_url) {
            if (isset($urls[$_url])) {
                return $_url;
            }
        }

        return array_keys($urls)[0];

    }

}